/*
 * @Description: 云卡首页
 * @ 请码逻辑介绍：
 * 1、获取失败行程次数协议失败不展示二维码，点击图标重新获取失败行程次数；
 * 2、获取余额协议失败不展示二维码，点击图标重新获取余额并请码；
 * 3、获取支付顺序协议失败，以默认余额支付，且未绑定银行卡作为请码判断条件，支付方式展示可刷新。
 * @Author: yingying.fan
 * @Date: 2019-03-29 20:55:46
 * @Last Modified by: yingying.fan
 * @Last Modified time: 2019-04-02 21:08:12
 */
<template>
  <div
    id="app"
    class="card-page-main-wrapper"
    :style="{backgroundColor:showCardInfo.bgColor,backgroundImage:'url('+showCardInfo.bgImage+')'}"
  >
    <!-- 标题栏 -->
    <title-bar>
      <div
        slot="right"
        class="title-right"
      >
        <i
          class="iconfont icon-w-paymeng"
          @click="goToMyWallet"
        ></i>
        <i
          class="iconfont icon-consumption"
          @click="goToConsumeList"
        ></i>
      </div>
    </title-bar>
    <!-- 下面这个div使用flex-v会导致部分样式隐藏 -->
    <div class="flex-h flex-hc flex-vc page-second-wrapper">
      <div class="flex-v">
        <!-- 失败行程提示模块 -->
        <div
          class="flex-h flex-vc recharge-warn"
          v-show="showFailHint"
          @click="goToPayOrderList"
        >
          <img src="./assets/warn.png">
          <p class="flex1">您有{{unpayCount}}笔行程扣款失败，请及时支付！</p>
          <i class="iconfont icon-rightangel baseColorNoAcitve"></i>
        </div>
        <!-- 卡列表 -->
        <card-swiper-list
          :cardInfoList="dataList"
          @clickQrcode="clickToRefresh"
          @changeCardInfo="changeCardInfo"
        ></card-swiper-list>
        <!-- 支付方式展示模块，最外层固定高度占位 -->
        <div
          class="blank-line"
          :class="{'pay-type-line-blank':showFailHint}"
        >
          <template v-if="showPayModule">
            <!-- 获取支付方式成功展示 -->
            <div
              class="flex-h flex-vc fontsize32 pay-type-line"
              v-if="getPaymentResult===1"
              @click="goToPaymentPage"
            >
              <p class="text-overflow-hide-1line">{{paymentName}}</p>
              <span
                class="flex1"
                v-html="paymentDesc"
              ></span>
              <i class="iconfont icon-rightangel"></i>
            </div>
            <!-- 获取支付方式失败展示 -->
            <div
              class="flex-h flex-vc fontsize32 pay-type-line"
              v-else-if="getPaymentResult===2"
              @click="refreshPayment"
            >
              <p class="flex1">点击重新获取支付方式</p>
              <refresh-img
                ref="refreshImg"
                :afterStartRefresh="getPaymentOrder"
              ></refresh-img>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { TitleBar } from 'vue-xb-ui-depot'
import { open, back } from '@/utils/JumpUtils.js'
import {
  getCardConfigCache,
  unequalToSetCache,
  setTradeCache
} from './utils/CardInfoCacheUtils.js'
import {
  getCardList,
  getInstanceConfig,
  getUnpaySuccessCount
} from './api/api.js'
import { BUS_CARD_INSTANCE } from '@/constants/CardInstance'
import RefreshImg from './components/refreshimg/RefreshImg'
import CardSwiperList from './components/cardlist/CardSwiperList'
export default {
  components: {
    'title-bar': TitleBar,
    'card-swiper-list': CardSwiperList,
    'refresh-img': RefreshImg
  },
  data() {
    return {
      getCodeTime: 0, // 用来打印获取了几次二维码
      qrcodeTimer: null, // 请求二维码的计时器
      qrcodeRepeatTime: window.prodInApp ? 60000 : 50000, // 1分钟请码一次
      // qrcodeRepeatTime: 5000, // 1分钟请码一次
      dataList: null, // 卡列表数据
      cardModuleList: [], // 卡实例列表
      showCardModule: null, // 当前展示的卡实例
      showCardInfo: {}, // 当前展示的卡信息
      failTimeLimit: 0, // 扣款是失败限制次数
      unpayCount: 0, // 失败行程数量,不为-1时代表请求成功了
      forbidPlugin: false // 是否使用了提高亮度的插件，pause要重新置回
    }
  },
  computed: {
    // 控制支付模块是否展示，只有已开通的卡片展示该模块
    showPayModule() {
      return this.showCardModule && this.showCardModule.$options.name === 'CardOpenModule'
    },
    getUnpayCountResult() {
      return this.$store.getters.getUnpayCountResult
    },
    getPaymentResult() {
      return this.$store.getters.getPaymentResult
    },
    paymentName() {
      return this.$store.getters.payName
    },
    paymentDesc() {
      return this.$store.getters.payDesc
    },
    showFailHint() {
      return this.unpayCount && this.unpayCount <= this.failTimeLimit
    }
  },
  mounted() {
    this.getCacheCardConfig()
    this.$nextTick(() => {
      this.getUnpayCount()
      this.getList()
      this.getCardConfig()
    })

    this.addEventBus()
    this.addPushListener()

    window.onResume = () => {
      console.log('~~~~~~~~~~~onResume')
      this.getCacheCardConfig()
      this.getUnpayCount()
      this.getList()
      // this.getCardConfig()
      this.addPushListener()
    }

    window.onPause = () => {
      console.log('~~~~~~~~~~~onPause')
      this.clearQrcodeTimer()
      this.resetPluginAbility()
      this.removePushListener()
    }
  },
  methods: {
    // 监听各个小模块中发出的事件
    addEventBus() {
      this.$EventBus.$on('clickQrcode', this.clickToRefresh)
      this.$EventBus.$on('forbidPlugin', this.forbidPluginAbility)
    },
    // 监听push刷卡成功通知
    addPushListener() {
      window.paymentSuccessJsCallBackFn = msg => {
        // if (!window.prodInApp) {
        // msg = '{"CARD_INSTANCE_ID":"jhx_buscard","CARD_TYPE_ID":0,"MESSAGE_TYPE":90101,"SNO":"1905092000000670","STATE":1,"TRADE_DETAIL_TYPE":13,"TXT":"1905092000000670"}'
        // }
        try {
          msg = JSON.parse(msg)
          let msgType = msg.MESSAGE_TYPE + ''
          if (msgType === '90101') {
            let tradeId = msg.TXT
            let cardInstanceId = msg.CARD_INSTANCE_ID
            if (cardInstanceId) {
              setTradeCache(tradeId)
              if (cardInstanceId === BUS_CARD_INSTANCE) {
                // 云卡刷卡成功页
                open('paymentsuccess.html?_tv=false&bus=1')
              } else {
                // 员工卡刷卡成功页
                open('paymentsuccess.html?_tv=false&staff=1')
              }
            }
          }
        } catch (error) {
          console.error('pusherror', error)
        }
      }
      this.$System.then(System => {
        System.registerPushListener('90101', 'paymentSuccessJsCallBackFn', () => { }, () => { })
      })
    },
    // 移除push刷卡成功通知
    removePushListener() {
      this.$System.then(System => {
        System.unRegisterPushListener('90101', () => { }, () => { })
      })
    },
    // 从缓存中获取卡配置
    getCacheCardConfig() {
      let config = getCardConfigCache()
      this.$store.dispatch('fetchCardConfig', config)
      this.failTimeLimit = this.$store.getters.qrcodePosBillLimit
    },
    // 获取失败行程数
    getUnpayCount() {
      return getUnpaySuccessCount().then(count => {
        this.$store.dispatch('fetchGetUnpayCountResult', 1)
        // this.getUnpayCountResult = 1
        this.judgeFailCount(count)
      }).catch(() => {
        // 只有之前还未获取失败行程数协议，才允许改变状态为失败
        if (this.getUnpayCountResult === 0) {
          this.$store.dispatch('fetchGetUnpayCountResult', 2)
        }
        // this.getUnpayCountResult = 2
        // 或许失败之后卡面不展示二维码
      })
    },
    // 判断失败行程数
    judgeFailCount(count = null) {
      if (count !== null) {
        this.unpayCount = count
      }
      // 只有大于管理端配置的限制值时，才强提醒
      if (this.unpayCount > this.failTimeLimit) {
        this.showConfirm()
      } else {
        this.$ConfirmBox.hide()
      }
      if (!this.qrcodeTimer) {
        this.startQrcodeTimer()
      }
    },
    // 获取卡信息
    getList() {
      // showConfirmDialog('您有5笔乘车扣款失败', window.takeBusFailHint, '立即支付', '暂不处理')
      getCardList().then(newList => {
        // let newList = body.LIST
        if (JSON.stringify(newList) !== JSON.stringify(this.dataList)) {
          this.resetShowCard()
          this.dataList = newList
        } else {
          this.showCardModule && this.changeCardInfo()
        }
      }).catch(() => {

      })
    },
    resetShowCard() {
      this.showCardModule = null
      this.showCardInfo = {}
    },
    // 获取卡相关的配置，出码限制以及最大失败次数
    getCardConfig() {
      getInstanceConfig().then(body => {
        // 将卡配置存入缓存中，下次进入页面生效
        // setCardConfigCache(body)
        // 如果获取到的和缓存中不相等的，更新缓存，并且更新store，如果有了卡模块，重新获取二维码
        let unequal = unequalToSetCache(body)
        if (unequal) {
          this.$store.dispatch('fetchCardConfig', body)
          this.failTimeLimit = this.$store.getters.qrcodePosBillLimit
          this.judgeFailCount()
          this.showCardModule && this.changeCardInfo()
        }
      })
    },
    // 卡片切换
    changeCardInfo(cardModule = null, cardInfo = null) {
      if (cardModule) {
        this.showCardModule = cardModule
        this.showCardInfo = cardInfo
        this.resetPluginAbility()
      }
      // console.log('showCardModule', this.showCardModule)
      if (!this.cardModuleList.includes(this.showCardModule)) {
        this.cardModuleList.push(this.showCardModule)
      }
      // 获取到卡片的支付方式之后再获取卡片二维码
      this.getPaymentOrder().then(() => {
        this.getCardQrCode()
      }).catch(() => {
        this.getCardQrCode()
      })
    },
    getPaymentOrder() {
      return this.showCardModule.getCardPaymentOrder().then(() => {
        // this.getPaymentResult = 1
        this.$store.dispatch('fetchGetPaymentResult', 1)
        return ''
      }).catch(error => {
        // this.getPaymentResult = 2
        this.$store.dispatch('fetchGetPaymentResult', 2)
        throw error
      })
    },
    // 获取当前卡片二维码，等待协议回来后60s之后再次请求
    getCardQrCode() {
      // 先把计时器先关闭
      this.clearQrcodeTimer()
      // 当页面是活动状态时才会请求二维码
      if (!window.pause) {
        this.getCodeTime++
        console.log(this.showCardInfo.cardNo + '获取二维码次数：', this.getCodeTime)
        this.showCardModule.getQrCodeImage().then(() => {
          // TODO: 定时器请码
          this.startQrcodeTimer()
        }).catch(() => {
          this.startQrcodeTimer()
        })
      }
    },
    // 开始计时器
    startQrcodeTimer() {
      if (this.getUnpayCountResult === 1) {
        this.qrcodeTimer = setTimeout(this.getCardQrCode, this.qrcodeRepeatTime)
      }
    },
    clearQrcodeTimer() {
      if (this.qrcodeTimer) {
        clearTimeout(this.qrcodeTimer)
        this.qrcodeTimer = null
      }
    },
    // 点击二维码图片刷新
    clickToRefresh() {
      if (this.getUnpayCountResult === 1) {
        // 获取失败次数成功了的话就去请码
        this.getCardQrCode()
      } else if (this.getUnpayCountResult === 2) {
        // 获取失败次数失败的话就重新获取
        this.getUnpayCount()
      }
    },
    // 恢复插件能力
    resetPluginAbility() {
      // 一开始禁止过，才能调用该方法
      if (this.forbidPlugin) {
        this.forbidPlugin = false
        console.log('~~~aaa: 恢复亮度,允许截屏')
        this.$System.then(System => {
          // 恢复亮度
          System.resetBrightness(() => { }, () => { })
          // 允许截屏
          window.x_system.allowScreenShots(() => { }, () => { }, '请勿外传二维码,以免造成不必要的损失')
        })
      }
    },
    // 禁止插件能力
    forbidPluginAbility() {
      // 一开始没禁止过，才能调用该方法
      if (!this.forbidPlugin) {
        this.forbidPlugin = true
        console.log('~~~aaa: 提高亮度,禁止截屏')
        this.$System.then(System => {
          // 提高亮度
          System.improveBrightness(() => { }, () => { })
          // 禁止截屏
          window.x_system.forbidScreenShots(() => { }, () => { }, '请勿外传二维码,以免造成不必要的损失')
        })
      }
    },
    // 刷新支付方式,击开始刷新动画
    refreshPayment() {
      // 开始刷新动画
      this.$refs.refreshImg.startRefresh()
    },
    // 失败行程超出限制后的强提示弹框
    showConfirm() {
      this.$ConfirmBox.show({
        title: '您有' + this.unpayCount + '笔乘车扣款失败',
        message: window.takeBusFailHint,
        confirmText: '立即支付',
        cancelText: '暂不处理'
      }).then(() => {
        // 跳转到支付失败行程页
        console.log('成功')
        this.goToPayOrderList()
      }).catch(() => {
        // 返回
        console.log('失败')
        back()
      })
    },
    // 跳转到失败行程页面
    goToPayOrderList() {
      open('payorderlist.html?_tv=false&from=cardinfo')
    },
    /**
     * 跳转到支付顺序页面
     */
    goToPaymentPage() {
      // 点击过了支付方式就将没张卡片中的支付方式清空，为了返回刷新能重新获取支付顺序
      this.cardModuleList.map(module => {
        module.clearPayment && module.clearPayment()
      })
      let params = 'cardinstanceid=' + this.showCardInfo.cardInstanceId + '&cardtype=' + this.showCardInfo.cardType
      open('deductionlist.html?_tv=false&' + params)
    },
    /**
     * 跳转到钱包
     */
    goToMyWallet() {
      open('mywallet.html?_tv=false')
    },
    /**
     * 跳转到账单列表
     */
    goToConsumeList() {
      open('consumelist.html?_rv=true')
    }
  }
}
</script>

<style>
html,
body {
  height: 100%;
  overflow: hidden;
  /* background-color: #cccccc; */
}
.card-page-main-wrapper {
  height: 100%;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  color: #333333;
  transition: background-color 0.5s;
}
/* 标题部分 */
.title-bar-wrapper {
  color: #ffffff;
}
.title-right {
  position: absolute;
  right: 0;
  overflow: hidden;
  font-size: 0;
}
.title-right > i {
  display: inline-block;
  overflow: visible;
  width: 50px;
  height: 50px;
  line-height: 50px;
  padding: 20px;
  vertical-align: middle;
  text-align: center;
}
.title-right > .icon-w-paymeng {
  font-size: 44px;
}
.title-right > .icon-consumption {
  font-size: 38px;
}
/* 充值提示  */
.recharge-warn {
  width: 600px;
  height: 60px;
  background-color: #ffffff;
  border-radius: 8px;
  margin: 0 auto 27px auto;
  font-size: 24px;
}
.recharge-warn > img {
  width: 40px;
  height: 40px;
  margin: 0 20px 0 25px;
}
.recharge-warn > i {
  font-size: 20px;
  font-weight: bold;
  margin-right: 30px;
}
.page-second-wrapper {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}
.page-second-wrapper > div {
  margin: auto;
  width: 100%;
}
/* 支付方式展示 */
.pay-type-line {
  width: 490px;
  height: 70px;
  padding: 0 50px 0 60px;
  color: #ffffff;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 35px;
  overflow: hidden;
}
.pay-type-line > i {
  font-size: 30px;
  margin-left: 12px;
}
.text-overflow-hide-1line {
  max-width: 55%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}
.blank-line {
  height: 70px;
  padding: 50px 0 20px 0;
  margin: 0 75px;
}
/* 当展示失败行程次数时，展示支付方式下的占位空白栏 */
.pay-type-line-blank {
  height: 160px;
}
</style>
